package ca.camosun.chatbox.network;

import java.io.IOException;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

public class AcceptThread extends Thread {
    private final BluetoothServerSocket mServerSocket;
    
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
 
    public AcceptThread() {
    	
        BluetoothServerSocket tmp = null;
        try {
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("Chat Box", UUID.fromString("b7a74330-7bdc-11e2-b92a-0800200c9a66"));
        } catch (IOException e) { }
        mServerSocket = tmp;
    }
 
    public void run() {
    	
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = mServerSocket.accept();
            } catch (IOException e) {
                break;
            }
            // If a connection was accepted
            if (socket != null) {
            	
            	ConnectedThread connection = new ConnectedThread(socket);
            	connection.start();
	
            	//Do something with the new connection.
                //Start the message receiver, I think.
            	
                try {
					mServerSocket.close();
				} catch (IOException e) {
					break;
				}
                break;
            }
        }
    }
 
    public void cancel() {
        try {
            mServerSocket.close();
        } catch (IOException e) { }
    }
}